<?php
/**
 * 店铺API
 */
namespace app\smartbc\controller\api\v1;
use app\smartbc\controller\api\Base;
use app\smartbc\model\SmartbcStore;
use app\smartbc\model\SmartbcStoreBill;
use app\smartbc\model\SmartbcStoreGroup;
use app\smartbc\model\SmartbcStoreUnion;
use app\smartbc\model\SmartbcCouponUser;
use app\smartbc\model\SmartbcOrder;
use app\smartbc\model\SmartbcCoupon;
use think\helper\Time;
use filter\Filter;

class Store extends Base{

    /**
     * 初始化当前应用管理员是不是联盟城市账户
     * @return void
     */
    public function initialize() {
        parent::initialize();
        $this->isUserAuth();
    }

    /**
     * 判断是否商家
     * @return boolean
     */
    public function isstore(){
        $store = SmartbcStore::manageStore($this->user->id);
        if ($store) {
            return enjson(200,$store);
        }
        return enjson(204,'你不是商家');
    }

    /**
     * 申请入驻商家/修改商家信息
     */
    public function edit(){
        if (request()->isPost()) {
            $param = [
                'name'      => $this->request->param('name/s'),
                'address'   => $this->request->param('address/s'),
                'telphone'  => $this->request->param('telphone/s'),
                'latitude'  => $this->request->param('latitude/s'),
                'longitude' => $this->request->param('longitude/s'),
                'imgs'      => $this->request->param('imgs/s','[]','htmlspecialchars_decode'),
            ];
            $rel = $this->apiSign($param);
            if ($rel['code'] != 200) {
                return enjson($rel['code'],'签名验证失败');
            }
            $validate = $this->validate($param,'Store.reg');
            if(true !== $validate){
                return enjson(403,$validate);
            }
            //判断是修改还是创建
            $store = SmartbcStore::manageStore($this->user->id);
            if($store){
                $data['is_lock']  = 1;
                $data['sort']     = 0;
            }
            $data['is_pass']           = 0;
            $data['member_miniapp_id'] = $this->miniapp_id;
            $data['manage_uid']        = $this->user->id;
            $data['name']              = $param['name'];
            $data['telphone']          = $param['telphone'];
            $data['address']           = $param['address'];
            $data['latitude']          = $param['latitude'];
            $data['longitude']         = $param['longitude'];            
            $imgs = Filter::filter_escape(json_decode($param['imgs'],true));
            if(!empty($imgs)){
                $data['imgs'] = json_encode(Filter::filter_escape(json_decode($param['imgs'],true)));
                $data['img']  = $imgs[0];
            }
            $rel = $store ? SmartbcStore::where(['id' => $store->id])->update($data) : SmartbcStore::create($data);
            if($rel){
                return enjson(200,"提交成功");
            }
            return enjson(403,"提交失败");
        }
    }

    //读取商家信息
    public function storeInfo(){
        $rel = $this->apiSign();
        if ($rel['code'] != 200) {
            return enjson($rel['code'],'签名验证失败');
        }
        //判断是修改还是创建
        $store = SmartbcStore::manageStore($this->user->id);
        if (!$store) {
            return enjson(404);
        }
        return enjson(200,$store);
    }

    //商家数据统计
    public function storeData(){
        $rel = $this->apiSign();
        if ($rel['code'] != 200) {
            return enjson($rel['code'],'签名验证失败');
        }
        //判断是修改还是创建
        $store = SmartbcStore::manageStore($this->user->id);
        if (!$store) {
            return enjson(404);
        }
        list($start, $end) = Time::yesterday();
        $amount     = SmartbcOrder::where([['store_id','=', $store->id],['state', '=',1],['update_time', '>=',$start],['update_time', '<=',$end]])->sum('price');
        $coupon     = SmartbcCoupon::where(['store_id' => $store->id])->count(); //已领取
        $couponuser = SmartbcCouponUser::where(['store_id' => $store->id])->where('parent_store_id','>',0)->count(); //引流
        $from       = SmartbcCouponUser::where([['store_id', '=', $store->id],['parent_store_id', '>',0],['money', '>',0],['is_end', '=',1]])->count(); //引流
        return enjson(200,['store'=>$store,'amount' => $amount,'coupon'=>$coupon,'couponuser' => $couponuser,'from'=> $from]);
    }

    //商家收入
    public function bill(){
        $param = [
            'page'           => $this->request->param('page/d',1),
            'store_id'       => $this->request->param('store_id'),
            'store_chain_id' => $this->request->param('store_chain_id'),
            'fixed_date'     => $this->request->param('fixed_date'),
            'times'          => $this->request->param('times','[]','htmlspecialchars_decode'),
        ];
        $rel = $this->apiSign($param);
        if ($rel['code'] != 200) {
            return enjson(500,'签名验证失败');
        }
        //判断是修改还是创建
        $store = SmartbcStore::manageStore($this->user->id);
        if (!$store) {
            return enjson(404);
        }
        $condition[] = ['member_miniapp_id','=',$this->miniapp_id];
        $condition[] = ['store_id', '=',$store->id];
        if($param['store_chain_id']){
            $condition[] = ['store_chain_id', '=',$param['store_chain_id']];
        }
        if($param['fixed_date'] == 3){
            $times = Filter::filter_escape(json_decode($param['times'],true));
            if(!empty($times['startime']) || !empty($times['endtime'])){
                $start  = strtotime($times['startime'].'00:00:00');
                $end   = strtotime($times['endtime'].'23:59:59');
                if($start >= $end){
                    return enjson(403,'开启日期禁止大于结束日期');
                } 
                $condition[] = ['update_time', '>=', $start];
                $condition[] = ['update_time', '<=', $end];
            }
        }else{
            switch ($param['fixed_date']) {
                case 1:
                    list($start, $end) = Time::yesterday();
                    break;
                case 2:
                     list($start, $end) = Time::month();
                    break;
                default:
                    list($start, $end) = Time::today();
                    break;
            }
            $condition[] = ['update_time', '>=', $start];
            $condition[] = ['update_time', '<=', $end];
        }
        $rel = SmartbcStoreBill::withAttr('update_time', function ($value, $data) {
            return date('Y-m-d H:i',$value);
        })->with(['user'=> function($query) {
            $query->field('id,face,nickname');
        }])->where($condition)->order('id desc')->page($param['page'],20)->select();
        if (empty($rel)) {
            return enjson(204);
        }
        $amount['inc']   = 0;
        $amount['dec']   = 0;
        $amount['order'] = 0;
        if($param['page'] == 1){
            $amount['inc']   = SmartbcStoreBill::where($condition)->where('money','>',0)->sum('money');
            $amount['dec']   = SmartbcStoreBill::where($condition)->where('money','<',0)->sum('money');
            $amount['order'] = SmartbcOrder::where($condition)->where('state','=',1)->sum('price');
        }
        return enjson(200,['bill' => $rel,'amount' => $amount]);
    }
}